<template>
	<view class="gy-avatar" :style="customStyle" @click.stop="">
		<image :src="proxy.utils.image.fullPath(showDefault ? props.default : props.src)" :style="customStyle" @error="showDefaultFn" @tap="previewFn" />
        <view v-if="props.badgeNumber" class="gy-avatar-badge-number">{{ props.badgeNumber }}</view>
    </view>
</template>

<script lang="ts" setup>
	
	import {
		ref,
		watch,
		computed,
		getCurrentInstance
	} from "vue";

    import config from "@/config/index.js";
	
	const { proxy } : any = getCurrentInstance();

    const props = defineProps({
    	src: {
    		type: String
    	},
        default: {
        	type: String,
            default: "d0d2f804a0ad84a57b71bff8fb1b896bda32eb02bc1b94323bf6a1cd7bc3704d.png"
        },
    	size: {
    		type: Number,
    		default: 100
    	},
    	radius: {
    		type: Number,
    		default: 10
    	},
        preview: {
        	type: Boolean,
            default: false
        },
        badgeNumber: {
        	type: Number,
        	default: 0
        }
    });

    const showDefault = ref(false);

    const customStyle = computed(() => {
        return {
            width: props.size + 'rpx',
            height: props.size + 'rpx',
            borderRadius: props.radius + 'rpx'
        }
    })

    function showDefaultFn(){
        showDefault.value = true;
    }

    function previewFn(){
        if(props.preview){
            let url = config.imgURL + (showDefault.value ? props.default : props.src);
			uni.previewImage({
			    current: url,
			    urls: [url]
			})
        }
    }
	
	watch(() => props.src, () => {
		showDefault.value = props.src ? false : true
	}, {immediate: true});

</script>

<style lang="scss" scoped>
	.gy-avatar{
	    position: relative;
		display: inline-block;
	    image{
	        max-width: 100%;
	        display: block;
	    }
	    .gy-avatar-badge-number{
	        position: absolute;
	        top: 0rpx;
	        right: 0rpx;
	        z-index: 1;
	        min-width: 30rpx;
	        height: 30rpx;
	        @include flex-center-center;
	        color: #ffffff;
	        border-radius: 15rpx;
	        background: var(--gy-color-error);
	        font-size: var(--gy-font-size-small);
	    }
	}
	
</style>
